package com.meilai.project.service.personnel.onTurn.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.personnel.onTurn.RegularApplyCheckDTO;
import com.meilai.project.dto.personnel.onTurn.RegularApplyDTO;
import com.meilai.project.dto.personnel.onTurn.RegularApplyListDTO;
import com.meilai.project.dto.workflow.FlowBusinessDataSuperEntity;
import com.meilai.project.dto.workflow.WorkFlowCheckDTO;
import com.meilai.project.entity.personnel.onTurn.RegularApply;
import com.meilai.project.entity.personnel.org.Roster;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.personnel.onTurn.RegularApplyMapper;
import com.meilai.project.mapper.system.UserMapper;
import com.meilai.project.service.personnel.onTurn.EntryApplyFamilyMemberService;
import com.meilai.project.service.personnel.onTurn.EntryApplyWorkExperienceService;
import com.meilai.project.service.personnel.onTurn.RegularApplyService;
import com.meilai.project.service.personnel.org.RosterService;
import com.meilai.project.service.system.impl.UserServiceImpl;
import com.meilai.project.util.ThreadLocalUserUtil;
import com.meilai.project.util.WorkFlowUtil;
import com.meilai.project.vo.personnel.onTurn.EntryApplyFamilyMemberVO;
import com.meilai.project.vo.personnel.onTurn.EntryApplyWorkExperienceVO;
import com.meilai.project.vo.personnel.onTurn.RegularApplyVO;
import com.meilai.project.vo.system.UserForWFVO;
import com.meilai.project.vo.system.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 入编申请 服务实现类
 * </p>
 *
 * @author xchen
 * @since 2022-01-20
 */
@Service
public class RegularApplyServiceImpl extends ServiceImpl<RegularApplyMapper, RegularApply> implements RegularApplyService {

    @Autowired
    private RosterService rosterService;
    @Autowired
    private EntryApplyFamilyMemberService entryApplyFamilyMemberService;
    @Autowired
    private EntryApplyWorkExperienceService entryApplyWorkExperienceService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<RegularApplyVO> selectPageList(RegularApplyListDTO searchDTO) {
        searchDTO.addOrderItem(Roster.BE_REGULAR, true);
        searchDTO.addOrderItem(Roster.COMP_FILL_PROBATION_END, true);
        searchDTO.addOrderItem(Roster.COMP_FILL_ENTRY_DATE, false);
        Page<RegularApplyVO> page = searchDTO.createPage(RegularApplyVO.class);
        List<RegularApplyVO> regularApplyVOS = baseMapper.selectPageList(page, searchDTO);
        page.setRecords(regularApplyVOS);
        return page;
    }

    @Override
    public RegularApplyVO getOneById(Long id, Long rosterId) {
        RegularApplyVO result = baseMapper.queryDetailById(id, rosterId);
        if (result == null) throw new CommonException("数据不存在！");
        if (null != id) {
            Long userId = ThreadLocalUserUtil.get().getId();
            Boolean canCheck = WorkFlowUtil.canCheckData(userId, result);
            result.setCan_check(canCheck);
            result.setIs_applyer(userId.equals(result.getFlow_applyer_id()));
        } else {
            result.setIs_applyer(true);
        }

        List<EntryApplyFamilyMemberVO> entryApplyFamilyMemberVOS = entryApplyFamilyMemberService.selectListByPid(result.getRoster_id());
        result.setFamily_members(entryApplyFamilyMemberVOS);
        List<EntryApplyWorkExperienceVO> entryApplyWorkExperienceVOS = entryApplyWorkExperienceService.selectListByPid(result.getRoster_id());
        result.setWork_experiences(entryApplyWorkExperienceVOS);
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean save(RegularApplyDTO dto) {
        int flowResult = saveAndBegin(dto, true);
        if (flowResult != 1) throw new CommonException("保存至草稿箱失败，请联系管理员！");
        else return true;
    }

    public int saveAndBegin(RegularApplyDTO dto, boolean isSave) {
        // 获取当前人的id和部门id
        UserForWFVO user = UserServiceImpl.getUserForWF(dto);
        RegularApply temp = new RegularApply();
        BeanUtils.copyProperties(dto, temp);

        // 设置流程字段，flow_type请自行对应“dict_flow_type”表中的id， 比如当前入职流程（考察登记流程）的id是5
        String flow_title = "入编申请"; // 审批流程的名称，需要根据实际业务自行确定
        FlowBusinessDataSuperEntity fbdse = WorkFlowUtil.getStartSuperDataEntity(
                user.getUser_id(),  // 当前用户id
                user.getDep_id(), // 提交的部门id
                8, // 流程类型id，“dict_flow_type”表中的id
                flow_title // 自定义的流程标题
        );
        BeanUtils.copyProperties(fbdse, temp);

        // 是否为新数据
        // 新数据时，前端不传业务数据id
        // 非新数据时，即来源是“草稿箱”、“已删除”、“被退回”时，前端需要传入业务数据id
        boolean isFirst = (dto.getId() == null);

        // 由于流程字段含有id，会覆盖数据，此处需要手动setId
        if (!isFirst) temp.setId(dto.getId());

        // 新增或更新业务数据
        Roster roster = rosterService.getById(dto.getRoster_id());
        Long user_id = roster.getUser_id();
        UserVO userVO = userMapper.getUserVOById(user_id);
        temp.setComp_fill_belong_dep_id(userVO.getMain_department_id());
        temp.setComp_fill_belong_dep(userVO.getMain_department_name());
        temp.setComp_fill_job(userVO.getMain_department_job());
        boolean flag = isFirst ? save(temp) : updateById(temp);
        if (!flag) throw new CommonException("保存失败");

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<RegularApply, RegularApplyMapper>(temp.getId(), user.getUser_id(), RegularApply.class);

        // 审批流程id
        // 新数据,传0L
        // 非新数据,根据数据id,查找wfData_id
        Long wfData_id = isFirst ? 0L : wfu.getWfDataId(dto.getId());
        // 旧数据记录留存
        RegularApply old_data = isFirst ? new RegularApply() : temp;

        return isSave ? wfu.SaveDraft(wfData_id) : wfu.Begin(wfData_id, "", old_data);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean begin(RegularApplyDTO dto) {
        // 提交
        int flowResult = saveAndBegin(dto, false);
        if (flowResult == 1) {
            // 仍在流程中
            return true;
        } else if (flowResult == 2) {
            // 无审批节点，直接结束
            endProcess(dto.getId());
            return true;
        } else {
            throw new CommonException("提交失败，请联系管理员！");
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean pass(RegularApplyCheckDTO dto) {
        // 通过
        int flowResult = passAndBack(dto, true, false);
        if (flowResult == 1) {
            // 通过后仍然在流程中
            return true;
        } else if (flowResult == 2) {
            // 审核后流程结束
            // 更新roster表
            endProcess(dto.getId());

            return true;
        } else {
            throw new CommonException("通过失败，请联系管理员！");
        }
    }

    public void endProcess(Long id) {
        RegularApply item = getById(id);
        Roster roster = new Roster();
        roster.setId(item.getRoster_id());
        roster.setBe_regular(1);
        roster.setRegular_apply_id(item.getId());
        roster.setContract_sign_at(item.getContract_sign_at());
        roster.setYears_begin(item.getYears_begin());
        roster.setYears_end(item.getYears_end());
        roster.setSign_confidentiality_agree(item.getSign_confidentiality_agree());
        roster.setAttachment_contract(item.getAttachment_contract());
        roster.setAttachment_con_agree(item.getAttachment_con_agree());
        roster.setComp_fill_entry_date(item.getComp_fill_entry_date());
        roster.setComp_fill_salary(item.getComp_fill_salary());
        roster.setComp_fill_salary_remark(item.getComp_fill_salary_remark());
        rosterService.updateById(roster);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean returnBack(RegularApplyCheckDTO dto) {
        // 驳回
        int flowResult = passAndBack(dto, false, false);
        if (flowResult != 1) throw new CommonException("驳回失败，请联系管理员！");
        return true;
    }

    // 通过 和 驳回 抽出相同代码
    private int passAndBack(RegularApplyCheckDTO dto, boolean isPass, boolean... updateData) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 若业务数据有审批中可修改的内容，请自行更新
        if (updateData != null && updateData[0]) {
            RegularApply updateTemp = new RegularApply();
            BeanUtils.copyProperties(dto, updateTemp);
            updateById(updateTemp);
        }

        // 业务数据
        RegularApply temp = getById(dto.getId());

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<RegularApply, RegularApplyMapper>(dto.getId(), userId, RegularApply.class);

        // 审批入参类
        WorkFlowCheckDTO checkDTO = WorkFlowCheckDTO.getWorkFlowCheckDTO(
                temp.getFlow_current_node_id(), // 当前节点id
                temp.getFlow_json(), // 流程json
                dto.getWf_check_opinion(), // 审批意见
                dto.getWf_check_sign_url(), // 审批签名链接
                JSONObject.toJSONString(temp) // 旧数据留存
        );

        // 审批
        return isPass ? wfu.ToNext(checkDTO) : wfu.ReturnBack(checkDTO);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean delete(Long id) {
        int flowResult = deleteAndActualDel(id, false);
        if (flowResult != 1) throw new CommonException("删除失败，请联系管理员！");
        return true;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean actualDelete(Long id) {
        int flowResult = deleteAndActualDel(id, true);
        if (flowResult != 1) throw new CommonException("彻底删除失败，请联系管理员！");
        return true;
    }

    // 删除 和 彻底删除 抽出相同代码
    private int deleteAndActualDel(Long id, boolean isActual) {
        // 当前人id
        Long userId = ThreadLocalUserUtil.get().getId();

        // 构造流程工具类
        WorkFlowUtil wfu = new WorkFlowUtil<RegularApply, RegularApplyMapper>(id, userId, RegularApply.class);

        // 流程id
        Long wfData_id = wfu.getWfDataId(id);

        return isActual ? wfu.ActualDelete(wfData_id) : wfu.Delete(wfData_id);
    }
}
